package com.a.b.c.d.e.webmagic.processors;

import com.a.b.c.d.e.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;
import us.codecraft.webmagic.selector.Selector;

import java.sql.Time;
import java.util.*;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Created on 2021/9/15.
 *
 * @author yanshuchun
 */
@Slf4j
public class GupiaoProcessor implements PageProcessor {
    public static final String base_url = "http://hq.sinajs.cn/list=";
    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

    @Override
    public void process(Page page) {
        String url = page.getUrl().get();
        String substring = url.substring(url.lastIndexOf("_") + 1, url.lastIndexOf("."));
        Html html = page.getHtml();
        List<String> params = new ArrayList<>();
        for (int i = 0; ; ) {
            String text = html.css("#ctrlfscont > ul:nth-child(1) > li:nth-child(" + ++i + ") > a", "text").get();
            if (ObjectUtils.isEmpty(text) || i > 1) {
                break;
            }

            params.add(substring + getNumAndName(text));
            if (i % 100 == 0) {
                check(params);
                params = new ArrayList<>();
            }
        }
        check(params);

    }

    public String getNumAndName(String text) {
        String substring = text.substring(text.indexOf("(") + 1, text.indexOf(")"));
        return substring;
    }

    public void check(List<String> paramsList) {
        String params = paramsList.stream().collect(Collectors.joining(","));
        try {
            checkAgain(HttpUtil.get(base_url + params, null, null));
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void checkAgain(String s) {
        if (!StringUtils.isEmpty(s)) {
            List<String> strings = Arrays.asList(s.split(";"));
            strings.stream().forEach(item -> {
                if (item.length() > 10) {
                    String substring = item.substring(item.lastIndexOf("=") + 2, item.lastIndexOf("\""));
                    List<String> res = Arrays.asList(substring.split(","));
                    int i = Integer.valueOf(res.get(10)) / 100;
                    System.out.println("名称：" + res.get(0) +
                            " 今日开盘价:" + res.get(1) +
                            " 昨日收盘价:" + res.get(2) +
                            " 当前价格:" + res.get(3) +
                            " 今日最高价:" + res.get(4) +
                            " 今日最低价:" + res.get(5) +
                            " 竞买价，即“买一”报价:" + res.get(6) +
                            " 竞卖价，即“卖一”报价:" + res.get(7) +
                            " 成交的股票数:" + res.get(8) +
                            " 成交金额:" + res.get(9) +
                            " 买一:" + res.get(10) +
                            " 买一报价:" + res.get(11) +
                            " 时间:" + res.get(31));
                }
                ;


            });

        }
    }

    @Override
    public Site getSite() {
        System.out.println("获取访问站点++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        return site;
    }

    public static void main(String[] args) {
//        String a = null;
//        Optional<String> a1 = Optional.ofNullable(a);
//        System.out.println(a1);
//        System.out.println(a1.orElse(null));
        System.out.println(System.nanoTime());
        System.out.println(System.currentTimeMillis());
        DelayQueue<QueueDelay> delays = new DelayQueue<>();
        for (int i = 0;i<10;i++){
            QueueDelay queueDelay = new QueueDelay(TimeUnit.NANOSECONDS.convert(3,TimeUnit.SECONDS));
            delays.put(queueDelay);
            try {
                delays.take().do_();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    static class QueueDelay implements Delayed {

        private Long timeout;
        public QueueDelay(Long timeout){
            this.timeout = timeout+System.nanoTime();
        }
        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(timeout - System.nanoTime(), TimeUnit.NANOSECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            if(this == o){
                return 0;
            }
            long l = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
            return l==0l?0:l<0?-1:1;
        }

        public void do_(){
            System.out.println("123");
        }
    }

}
